<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 模拟tab产生空格
 * @param int $step
 * @param string $string
 * @param int $size
 * @return string
 */
function tab($step = 1, $string = ' ', $size = 4)
{
    return str_repeat($string, $size * $step);
}

/**统一接口返回格式
 * @param $data
 * @param int $code
 * @param string $msg
 * @return \think\response\Json
 */
function json_success($data,$code=100000,$msg='操作成功'){
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    return json($result);
}
/**APP统一成功接口返回格式
 * @param $data
 * @param string $code
 * @param string $msg
 * @return \think\response\Json
 */
function json_app_success($data='',$code='100000',$msg='操作成功'){
    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    return json($result);
}

function json_failed($code,$msg=''){
    $codeMsg = config('error.'.$code);
    if(empty($msg)){
        $msg = $codeMsg;
    }
    $result = [
        'code' => $code,
        'msg' => $msg
    ];

    return json($result);
}
/**
 * CURL请求
 * @param $url      --请求url地址
 * @param $method   --请求方法 get post
 * @param null      --$postFields post数据数组
 * @param array     --$headers 请求header信息
 * @param bool|false $debug  --调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
}

/**
 * curl get请求
 */
function curl_get($url,&$httpCode = 0){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * curl post请求
 */
function curl_post($url, $data = NULL, $options=''){
    $param = json_encode($data);
    //echo $param;
    if (!$url) {
        return false;
    }
    if (!$data) {
        return false;
    }
    $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(!empty($options)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data); // 如果为数组，调用http_build_query
//        $output = json_decode(curl_exec($ch), true);
    $output = curl_exec($ch);
    //echo "send msg result---> {$output}\n";
    if (curl_errno($ch)) { // 出错则显示错误信息
        return false;
    }
    curl_close($ch);
    return $output;
}

//UUID 长度定为32位 超过截取
function create_uuid($prefix = ""){    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str,0,8);
    $uuid .= substr($str,8,4);
    $uuid .= substr($str,12,4);
    $uuid .= substr($str,16,4);
    $uuid .= substr($str,20,12);
    $uid =  $prefix . $uuid;
    if(strlen($uid)>32){
        $uid = substr($uid,0,32);
    }
    return $uid;
}
//长度为12位 不重复数字码 (为避免重复 尽量传uid）
function create_document_no($uid = ""){
    $uid = substr($uid,-3);
    $uid .=rand(100,999);
    $str =uniqid(mt_rand());
    $uid .= substr($str,0,12-strlen($uid));
    return $uid;
}

function trimall($str)//删除空格
{
    $qian=array(" ","　","\t","\n","\r");$hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}

function getIp(){
    $unknown = 'unknown';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    /*
    处理多层代理的情况
    或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
    */
    if (false !== strpos($ip, ','))
        $ip = reset(explode(',', $ip));
    return $ip;
}
/**
 * 根绝ip获取城市名
 * return $city
 */
function getLocationByIp($ip)
{
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
    $res = file_get_contents($url);
    $result = json_decode($res, true);
    if($result['code'] == 0){
        return $result['data']['city'];
    }else{
        return false;
    }
}

/**
 * 获取当天00：00：00 -- 23：59：59 时间戳
 */
function todayTime(){
    $start = mktime(0,0,0,date("m"),date("d"),date("Y"));//当天开始时间戳
    $end   = mktime(23,59,59,date("m"),date("d"),date("Y"));//当天结束时间戳
    $today = array('start'=>$start,'end'=>$end);
    return $today;
}

/**
 * 获取过去几天00：00：00 -- 23：59：59 时间戳
 */
function lastDay($day){
    $start = mktime(0,0,0,date("m"),date("d")-$day,date("Y"));//当天开始时间戳
    $end   = mktime(23,59,59,date("m"),date("d")-$day,date("Y"));//当天结束时间戳
    $today = array('start'=>$start,'end'=>$end);
    return $today;
}

/**
 * 获取本周起始时间戳和结束时间戳
 */
function weekTime(){
    $start = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));
    $end   = mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y'));
    $week  = array('start'=>$start,'end'=>$end);
    return $week;
}

/**
 * 获取本月起始时间戳和结束时间戳
 */
function monthTime(){
    $start = mktime(0,0,0,date('m'),1,date('Y'));
    $end   = mktime(23,59,59,date('m'),date('t'),date('Y'));
    $month  = array('start'=>$start,'end'=>$end);
    return $month;
}

/**
 * 数组转对象
 */
if (!function_exists('array2object')) {
    function array2object($array)
    {
        if (is_array($array)) {
            $obj = new StdClass();
            foreach ($array as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $array;
        }
        return $obj;
    }
}

//获取微信的access_token用于发送模板消息
if(!function_exists('wx_get_token')) {
    function wx_get_token()
    {
        $token = cache('access_token');
        if (!$token) {
            $appid = \think\Config::get('weixin.appid');
            $secret = \think\Config::get('weixin.appsecret');
            $res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret");
            $res = json_decode($res, true);
            $token = $res['access_token'];
            cache('access_token', $token, 3600);
        }
        return $token;
    }
}

/**
 * 概率
 */
function get_rand($proArr) {
    $result = array();
    $arr = [];
    foreach ($proArr as $key => $val) {
        $arr[$key] = $val['v'];
    }
    // 概率数组的总概率
    $proSum = array_sum($arr);
    asort($arr);
    // 概率数组循环
    foreach ($arr as $k => $v) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $v) {
            $result = $proArr[$k];
            break;
        } else {
            $proSum -= $v;
        }
    }
    return $result;
}

//function createCode($user_id) {
//    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
//    $num = $user_id;
//    $code = '';
//    while ( $num > 0) {
//        $mod = $num % 35;
//        $num = ($num - $mod) / 35;
//        $code = $source_string[$mod].$code;
//    }
//    if(empty($code[3]))
//        $code = str_pad($code,6,'0',STR_PAD_LEFT);
//    return $code;
//}


function createCode() {
    $code = rand(100000,999999);
    $data = \think\Db::name('user')->where('sid',$code)->find();
    if($data){
        createCode();
    }
    return $code;
}
//function decode($code) {
//    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
//    if (strrpos($code, '0') !== false)
//        $code = substr($code, strrpos($code, '0')+1);
//    $len = strlen($code);
//    $code = strrev($code);
//    $num = 0;
//    for ($i=0; $i < $len; $i++) {
//        $num += strpos($source_string, $code[$i]) * pow(35, $i);
//    }
//    return $num;
//}



function addLog($str) {
    $date = date('Ymd');
    $logPath =  '/usr/local/nginx/html/web5/sshb/runtime/log/userLogs';
    if (!file_exists($logPath)) {
        mkdir($logPath);
    }
    $logFile = $logPath . '/user_' . $date . '.log'; //文件名自定义
    $fp = file_put_contents($logFile, $str, FILE_APPEND);
    return true;
}

function isMobile($value)
{
    $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
    $result = preg_match($rule, $value);
    if ($result) {
        return true;
    } else {
        return false;
    }
}

function random($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}



function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
{

    $ch = curl_init();//初始化curl

    $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

    curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
    curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
    curl_setopt($ch, CURLOPT_SSLCERT, '/usr/local/nginx/html/web5/sshb/extend/wxpay/cert/apiclient_cert.pem');//证书位置
    curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
    curl_setopt($ch, CURLOPT_SSLKEY, '/usr/local/nginx/html/web5/sshb/extend/wxpay/cert/apiclient_key.pem');//证书位置

    if (count($aHeader) >= 1) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
    }
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//全部数据使用HTTP协议中的"POST"操作来发送

    $data = curl_exec($ch);//执行回话

    if ($data) {
        curl_close($ch);
        return $data;
    } else {
        $error = curl_errno($ch);
        echo "call faild, errorCode:$error\n";
        curl_close($ch);
        return false;
    }
}

//生成数字和字母组合随机数
function randomkeys($length) {
    $returnStr='';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern {mt_rand ( 0, 61 )};
    }
    return $returnStr;
}

//签名算法
function makeSignature($args,$key)
{
    ksort($args);
    $stringA = '';
    $stringSignTemp = '';
    foreach($args as $k => $v) {
        $stringA .= $k . '=' . $v . '&';
    }
    $stringSignTemp .=  $stringA.'key='.$key;
    $signature  = strtoupper(md5($stringSignTemp));
    return $signature;
}

//遍历数组方法
function arraytoxml($data){
    $str='<xml>';
    foreach($data as $k=>$v) {
        $str.='<'.$k.'>'.$v.'</'.$k.'>';
    }
    $str.='</xml>';
    return $str;
}